package com.lv.suyiyong.hfr.ui

import android.text.TextUtils
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseActivity
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.PageNameIdBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.WholeSalerSearch
import com.lv.service.repo.WholeSalerSearchDbHelper
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.WholeGoodsAdapter
import com.lv.suyiyong.hfr.databinding.ActivityWholeSalerSearchResultBinding
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/6 10:33 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：批发好价搜索结果页面
 */
@Route(path = ARoutUtils.WholeSalerSearchResultActivity)
class WholeSalerSearchResultActivity : BaseActivity<ActivityWholeSalerSearchResultBinding>(),
    View.OnClickListener {
    @Autowired(name = "search")
    @JvmField
    var search: String = ""

    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private val mBeans = mutableListOf<GoodsItemBean>()

    private var mAdapter: WholeGoodsAdapter? = null
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private val serviceViewModel: ServiceViewModel by viewModel()
    override fun getLayoutRes() = R.layout.activity_whole_saler_search_result
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@WholeSalerSearchResultActivity, viewTop)
            initSingleClickListener(ivBackTop, ivDelete, viewSearch)
        }
    }


    override fun initConfig() {
        super.initConfig()
        initAdapter()
        if (search.isNotEmpty()) {
            mBinding.searchVM = search
        }
        saleByBulk()
    }

    private fun initAdapter() {
        val gridLayoutManager = GridLayoutManager(this, 3)
        mBinding.rvContent.layoutManager = gridLayoutManager
        mAdapter = WholeGoodsAdapter(mBeans)
        mBinding.rvContent.adapter = mAdapter
        mBinding.rvContent.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(5.0f), SizeUtils.dp2px(5.0f), true
            )
        )
    }

    override fun initData() {
        super.initData()
    }

    private fun saleByBulk() {
        val body = PageNameIdBody(page, pageSize, search, emptyList())
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    serviceViewModel.saleByBulk(body)
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<GoodsBean> { code, data, message, result ->
                val items = data?.items
                MyUtils.recyclerviewSetData(
                    page, pageSize, mBinding.refresh, mBeans, items, mAdapter
                )
                if (mBeans.isEmpty()) {
                    mAdapter?.setEmptyView(getEmptyView(mBinding.rvContent))
                }
            }
            onBizError<GoodsBean> { code, message, data ->

            }
        }
        data.onFailure {

        }
    }


    override fun initEvents() {
        super.initEvents()

        mBinding.etSearch.setOnEditorActionListener { v, actionId, event ->
            KeyboardUtils.hideSoftInput(mBinding.etSearch)
            search = mBinding.etSearch.text.toString().trim()
            if (TextUtils.isEmpty(search)) {
                showToast("请输入搜索关键字")
                false
            } else {
                saveSearchWord(search)
                true
            }
        }

        mBinding.etSearch.addTextChangedListener { text ->
            if (TextUtils.isEmpty(text)) {
                search = ""
                mBinding.etSearch.paint.isFakeBoldText = false
            } else {
                search = text.toString()
                mBinding.etSearch.paint.isFakeBoldText = true
            }
        }
        mBinding.refresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                saleByBulk()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                saleByBulk()
            }
        })

    }

    private fun saveSearchWord(searchWord: String) {
        if (search != searchWord && searchWord.isNotEmpty()) {
            val homeSearch = WholeSalerSearch(searchWord, searchWord, false)
            WholeSalerSearchDbHelper.insertWholeSalerSearch(
                this@WholeSalerSearchResultActivity,
                homeSearch
            )
            search = searchWord
        }
        mBinding.refresh.autoRefresh()
//        mEditorViewModel.obCommon.postValue(CommonTab(search, tag = mCurrentTab))
        //发消息通知列表刷新
//        LiveEventBus
//            .get(LiveEventUtils.REFRESH_SEARCH_PAGE_KEY, String::class.java)
//            .post("HomeSearchActivity")
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back_top -> finish()
            R.id.iv_delete -> {
                mBinding.searchVM = ""
                search = ""
            }

            R.id.view_search -> {
                mBinding.searchVM = ""
                mBinding.etSearch.setText(search)
                mBinding.etSearch.setSelection(search.length)
            }

        }
    }


}